package cz.hanis.android.pubaccounting;

import java.util.ArrayList;
import java.util.List;

import cz.hanis.android.pubaccounting.app.PubAccountingApp;
import cz.hanis.android.pubaccounting.model.Pub;
import cz.hanis.android.pubaccounting.tools.DataHandler;
import android.app.Application;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class PubListActivity extends ListActivity {

	private PubAccountingApp app;
	
	private PubListAdapter adapter;
	
	private List<Pub> pubs;
	
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pub_list);
		app = (PubAccountingApp) getApplication();
		pubs = new ArrayList<Pub>();		
		adapter = new PubListAdapter(this, pubs);
		setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.pub_list_menu, menu);
		return true;
	}
	
	@Override
	protected void onResume() {	
		super.onResume();
		pubs.clear();
		pubs.addAll(app.getDbManager().getPubHeaders());
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.pub_list_new_pub:
			startNewPubActivity();
			return true;

		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void startNewPubActivity() {
		Intent intent = new Intent(this, PubEditingActivity.class);
		startActivity(intent);
	}
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {	

		long pubId = ((Pub)l.getItemAtPosition(position)).getId();
		Log.d("onlistitemclick", String.valueOf(pubId));
		Intent intent = new Intent(this, PubDetailActivity.class);
		intent.putExtra(PubDetailActivity.PUB_ID_KEY, pubId);
		startActivity(intent);		
	}

}
